﻿using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using XMFramework.Models;
using XMFramework.MysqlService;

namespace XMFramework.Forms.Pages.Devices
{
    public partial class FDevice : UIPage
    {
        private SqlSugarScope db = SqlSugarHelper.Db;
        List<DeviceModel> orderlist = new List<DeviceModel>();
        public FDevice()
        {
            InitializeComponent();
        }

        private void FDevice_Initialize(object sender, EventArgs e)
        {
            //每次打开页面初始化
            uiDatePicker1.Text = DateTime.Now.ToString("yyyy-MM-dd");

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                db.BeginTran();
                orderlist = db.Queryable<DeviceModel>().OrderBy(it => it.id, OrderByType.Desc).ToList();
                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            uiDataGridView1.DataSource = orderlist;
            uiSymbolButton2.Enabled = false;
            uiSymbolButton5.Enabled = false;
        }

        private void uiDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                uiTextBox3.Text = uiDataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString();//id
                uiComboBox1.Text = uiDataGridView1.Rows[e.RowIndex].Cells["deviceType"].Value.ToString();//设备类型
                uiTextBox1.Text = uiDataGridView1.Rows[e.RowIndex].Cells["deviceCode"].Value.ToString();//设备号
                uiTextBox2.Text = uiDataGridView1.Rows[e.RowIndex].Cells["pn"].Value.ToString();//网关pn
                uiTextBox6.Text = uiDataGridView1.Rows[e.RowIndex].Cells["notes"].Value.ToString();//备注

                uiSymbolButton2.Enabled = true;
                uiSymbolButton5.Enabled = true;
                UIMessageTip.ShowOk("调用 - 状态");
            }
        }

        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            //新增按钮
            DeviceModel dataList = new DeviceModel()
            {
                deviceType = uiComboBox1.Text,
                deviceCode = uiTextBox1.Text,
                pn = uiTextBox2.Text,
                creationDate = Convert.ToDateTime(uiDatePicker1.Text),
                notes = uiTextBox6.Text
            };

            try
            {
                db.BeginTran();

                //int count = db.Insertable(dataList).ExecuteCommand();//插入数据

                var x = db.Storageable(dataList)
                    .WhereColumns(it => new{ it.deviceCode })
                    .ToStorage();
                x.AsInsertable.ExecuteCommand();//不存在插入
                //x.AsUpdateable.IgnoreColumns(z => z.id).ExecuteCommand();//存在更新

                db.CommitTran();
                if (x.InsertList.Count > 0)
                    UIMessageTip.ShowOk("新增设备 - 成功");
                else
                    UIMessageTip.ShowWarning("已有设备 - 警告");
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton5_Click(object sender, EventArgs e)
        {
            //更新按钮
            try
            {
                db.BeginTran();

                bool datafalg = db.Queryable<ProductionOrderModel>()
                    .Any(it => it.deviceCode == uiTextBox1.Text);

                if (datafalg == true)
                {
                    UIMessageTip.ShowWarning("设备已绑定订单 - 无法更新");
                }
                else
                {
                    int count = db.Updateable<DeviceModel>()
                    .SetColumns(it => new DeviceModel()
                    {
                        deviceType = uiComboBox1.Text,
                        deviceCode = uiTextBox1.Text,
                        pn = uiTextBox2.Text,
                        creationDate = Convert.ToDateTime(uiDatePicker1.Text),
                        notes = uiTextBox6.Text
                    })
                    .Where(it => it.id == Convert.ToInt32(uiTextBox3.Text)).ExecuteCommand();
                    if (count > 0)
                        UIMessageTip.ShowOk("更新设备 - 成功");
                    else
                        UIMessageTip.ShowWarning("未查询到设备 - 警告");
                }
                db.CommitTran(); 
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton2_Click(object sender, EventArgs e)
        {
            //删除按钮
            try
            {
                db.BeginTran();

                bool datafalg = db.Queryable<ProductionOrderModel>()
                    .Any(it => it.deviceCode == uiTextBox1.Text);

                if (datafalg == true)
                {
                    UIMessageTip.ShowWarning("设备已绑定订单 - 无法删除");
                }
                else
                {
                    int count = db.Deleteable<DeviceModel>().Where(it => it.id == Convert.ToInt32(uiTextBox3.Text)).ExecuteCommand();
                    if (count > 0)
                        UIMessageTip.ShowOk("删除设备 - 成功");
                    else
                        UIMessageTip.ShowWarning("未查询到设备 - 警告");

                }
                db.CommitTran();

                
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton3_Click(object sender, EventArgs e)
        {
            //搜索按钮
            try
            {
                db.BeginTran();

                uiDataGridView1.DataSource = db.Queryable<DeviceModel>().
                    Where(it => it.deviceCode.Contains(uiTextBox5.Text) && it.pn.Contains(uiTextBox7.Text)).
                    OrderBy(it => it.id, OrderByType.Desc).ToList();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            uiSymbolButton2.Enabled = false;
            uiSymbolButton5.Enabled = false;
        }

        private void uiSymbolButton4_Click(object sender, EventArgs e)
        {
            //清除按钮
            uiTextBox5.Clear();//设备号
            uiTextBox7.Clear();//网关pn

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

    }
}
